﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using HandyControl.Controls;
using MyHelper;


namespace weighing
{
    /// <summary>
    /// ActiveWindow.xaml 的交互逻辑
    /// </summary>
    public partial class ActiveWindow : GlowWindow
    {

        private bool isActiving = false;

        public ActiveWindow()
        {
            InitializeComponent();

            CommonFunction.ShowCustomIcon(this);
        }
        #region window events
        private void GlowWindow_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void GlowWindow_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Escape) this.Close();
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ActiveBtn_Click(object sender, RoutedEventArgs e)
        {
            string code = this.ActiveCodeTb.Text.Trim();
            if (isActiving) { return; }
            isActiving = true;
            this.activeBtn.IsChecked = true;
            bool isValidCode = false;
            bool isGernalCode = ActiveCodeHelper.IsGernalCode(code);

            if (isGernalCode && !IsCanActiveCurrVersion(code))
            {
                string info = "激活码,不能激活该版本的系统，请重先输入。";
                Alert(info);
                return;
            }

            string msg;
            if (isGernalCode)
            {
                isValidCode = ActiveCodeHelper.AnalysisGernalCode(code);
            }
            else
            {
                isValidCode = ActiveCodeHelper.AnalysisCode(code);
            }
            if (!isValidCode)
            {
                msg = "非法的激活码，请重先输入。";
                Alert(msg);
                return;
            }

            var res = isGernalCode ? GernalActive(code) : ActiveCode(code);
            if (res)
            {
                msg = "激活成功，请重启动系统。";
                Alert(msg);
                this.Close();
                App.Current.Shutdown();
            }
            else
            {
                msg = "激活失败，请重先输入激活码。";
                Alert(msg);
            }
            isActiving = false;
        }

        private bool IsCanActiveCurrVersion(string code)
        {
            if (code == null || code.Length != 29 || !code.StartsWith("BN") || !code.EndsWith("HQ"))
            {
                return false;
            }
            string v = code.Substring(2, 1);
            if (v != "B" && v != "H")
            {
                return false;
            }

            string g = code.Substring(6, 1);
            if (g != "G")
            {
                return false;
            }
            string gv = code.Substring(6, 2);

            //return gv == "GB" || gv == "GH";
            return gv == "GB";
        }

        private bool GernalActive(string code)
        {
            var res = false;
            try
            {
                //1.保存激活码，和激活时间
                App.Config.ActiveCode = code;
                if (string.IsNullOrEmpty(App.Config.RadomKey)){
                    string RadomKey = EncryptHelper.Encrypto(code.Substring(0, 20));
                    App.Config.RadomKey = RadomKey;
                }
                else
                {
                    if (App.Config.RadomKey != EncryptHelper.Encrypto(code.Substring(0, 20)))
                    {
                        //无效激活码
                        Alert("激活码无效或已经使用");
                        return false ;
                    }
                }

                App.Config.ActiveTime = DateTime.Now;
                CommonFunction.UpdateAppConfig();
                res = true;
                //2.delete  激活码
                if (File.Exists(Constant.ActiveCodeFile))
                {
                    File.Delete(Constant.ActiveCodeFile);
                }
            }
            catch (Exception)
            {

            }
            return res;
        }

        private bool ActiveCode(string code)
        {
            if (code == App.Config.ActiveCode)
            {
                Alert();
                return false;
            }

            if (!FileHelper.Exists(Constant.ActiveCodeEncryptFile))
            {
                Alert();
                return false;
            }
            List<string> encriptCodes = FileHelper.ReadFileLines(Constant.ActiveCodeEncryptFile, Encoding.UTF8);

            if (encriptCodes.Count <= 0 || encriptCodes[0].Length < 20)
            {
                Alert();
                return false;
            }

            string encryptCode = encriptCodes[0];//第一行
            if (EncryptHelper.Encrypto(code) != encryptCode)//激活码不相等
            {
                Alert();
                return false;
            }

            //验证结束
            string RadomKey = EncryptHelper.Encrypto(ActiveCodeHelper.GeneraterCode().Substring(0, 20));

            //1.保存激活码，和激活时间
            App.Config.ActiveCode = code;
            App.Config.ActiveTime = DateTime.Now;
            App.Config.RadomKey = RadomKey;
            CommonFunction.UpdateAppConfig();

            //3. 随机替换原来的密文           
            FileHelper.Write(Constant.ActiveCodeEncryptFile, RadomKey);

            //4.delete  激活码
            try
            {
                if (File.Exists(Constant.ActiveCodeFile))
                {
                    File.Delete(Constant.ActiveCodeFile);
                }
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }


        private void Alert(string msg = "")
        {
            if (msg.IsNullOrEmpty())
            {
                msg = "该激活码无法激活软件，请联系软件服务商";
            }
            CommonFunction.AlertInfo(msg);
            isActiving = false;
            this.activeBtn.IsChecked = false;
            this.ActiveCodeTb.Focus();
        }

        private void ActiveCodeTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            var t = this.ActiveCodeTb.Text;
            if(ActiveCodeHelper.AnalysisCode(t) || ActiveCodeHelper.AnalysisGernalCode(t))
            {
                this.activeBtn.IsEnabled = true;
                this.ActiveCodeTb.ToolTip = "激活码可用";
            }
            else
            {
                this.activeBtn.IsEnabled = false;
                this.ActiveCodeTb.ToolTip = "激活码不可用";
            }
        }

        #region 申请激活码
        /// <summary>
        /// 申请激活码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ApplyCodeBtn_Click(object sender, RoutedEventArgs e)
        {

        }

        #endregion

      
    }
}
